package com.backend.controller;

import com.backend.entity.Result;
import com.backend.entity.ResultCode;
import com.backend.entity.dto.LoginDTO;
import com.backend.entity.dto.RepairmanRegisterDTO;
import com.backend.entity.dto.UserRegisterDTO;
import com.backend.entity.entity.Users;
import com.backend.entity.vo.LoginVO;
import com.backend.service.AuthService;
import com.backend.util.JWTUtil;
import com.backend.util.JwtUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 作者:xuSen
 * 日期2025/7/20 10:56
 * 登录注册接口
 */
@RestController
@RequestMapping("/api/auth")
@Tag(name = "登录注册模块接口")
@Slf4j
public class AuthController {
    @Autowired
    private AuthService authService;
    @Value("${backend.jwt.key}")
    private String key;
    //令牌的过期时间，以小时为单位
    @Value("${backend.jwt.expire}")
    private int expire;
    @Autowired
    private JwtUtils utils;

    @PostMapping("/register/user")
    @Operation(summary = "注册用户")
    public Result registerUser(@Valid @RequestBody UserRegisterDTO userRegisterDTO) {
        log.info("用户注册");

        // 调用service层
       String result = authService.registerUser(userRegisterDTO);
       // 判断
        if(result == null) {
            System.out.println("!!!!!!!!"+Result.success());
        return Result.success();}
        return Result.failure(ResultCode.BUSINESS_ERROR,result);
    }

    @PostMapping("/register/repairman")
    @Operation(summary = "注册维修工")
    public Result registerRepairman(@Valid @RequestBody RepairmanRegisterDTO RepairmanRegisterDTO) {
        log.info("维修工注册");
        // 调用service层
        String result = authService.registerRepairman(RepairmanRegisterDTO);
        // 判断
        if(result == null) return Result.success();
        return Result.failure(ResultCode.BUSINESS_ERROR,result);
    }
    @PostMapping("/login")
    @Operation(summary = "通用登录")
    public Result<LoginVO> login(@RequestBody  @Valid  LoginDTO loginDTO) {
        log.info("登录");
        // 调用service登录
        Users users=authService.login(loginDTO);
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userid", users.getUserId());
//        String user=users.getRole().toString();
        claims.put("roles", users.getRole().toString());
        System.out.println( claims);
        String token = JWTUtil.createJWT(
                key,// 签名
                expire,// 过期时间
                claims);
        LoginVO Loginvo = LoginVO.builder()
                .token(token)
                .userId(users.getUserId())
                .role(users.getRole())
                .phone(users.getPhone())
                .username(users.getUsername())
                .build();
        return Result.success(Loginvo);
    }
    @PostMapping("/logout")
    @Operation(summary = "退出登录")
    public Result logout(HttpServletRequest request) {
        // 获取token
        String authorization = request.getHeader("Authorization");
        if(utils.invalidateJwt(authorization)) {
            // 如果令牌成功列入黑名单，则返回成功信息
            return Result.success("退出登录成功");
        }
        return Result.failure(ResultCode.BUSINESS_ERROR,"退出登录失败");
    }
    @GetMapping("/token/refresh")
    @Operation(summary = "令牌刷新（延长有效期）")
    public Result<LoginVO> refreshToken(HttpServletRequest request) {
        // 获取请求头中的令牌
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return Result.failure(ResultCode.UNAUTHORIZED, "无效的令牌格式");
        }
        String token = authHeader.substring(7);

        try {
            // 解析令牌并验证是否有效
            Map<String, Object> claims = JWTUtil.parseJWT(key, token);
            if (claims == null) {
                return Result.failure(ResultCode.UNAUTHORIZED, "无效的令牌");
            }

            // 检查令牌是否在黑名单中
            String jti = claims.get("jti").toString();
            if (utils.isTokenBlacklisted(jti)) {
                return Result.failure(ResultCode.UNAUTHORIZED, "令牌已被注销");
            }

            // 生成新的令牌
            Map<String, Object> newClaims = new HashMap<>();
            newClaims.put("userid", claims.get("userid"));
            newClaims.put("roles", claims.get("roles"));
            String newJti = UUID.randomUUID().toString();
            newClaims.put("jti", newJti);
            String newToken = JWTUtil.createJWT(key, expire, newClaims);

            // 构建返回结果
            LoginVO loginVO = LoginVO.builder()
                    .token(newToken)
                    .userId(Integer.valueOf(claims.get("userid").toString()))
                    .role(Integer.valueOf(claims.get("roles").toString()))
                    .build();

            return Result.success(loginVO);
        } catch (Exception e) {
            log.error("令牌刷新失败", e);
            return Result.failure(ResultCode.UNAUTHORIZED, "令牌已过期，请重新登录");
        }
    }

}
